package com.axjy.web;


import com.axjy.pojo.Role;
import com.axjy.service.RoleService;
import com.axjy.util.Log;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/sys/role")
public class RoleHandler {

    @Resource
    private RoleService roleService;

    private String msg;

    @GetMapping("/list")
    @ResponseBody
    public List<Role> list(){
        return roleService.list();
    }

    @PostMapping("/add")
    @ResponseBody
    public String add(Role role ){
        try{
            roleService.add(role);
            msg="角色添加成功！";
        }catch (RuntimeException ex){
            msg="角色添加失败！";
        Log.getLogger().error(msg,ex);
        }
        return msg;
    }


    @PostMapping("/update")
    @ResponseBody
    public String update(Role role, HttpSession session){
        Role loginUser = (Role) session.getAttribute("loginUser");
        if (loginUser!=null){
            role.setName(loginUser.getName());
        }
        try {
            roleService.update(role);
            msg="角色修改成功!";
        }catch (RuntimeException ex){
            msg="角色修改失败";
            Log.getLogger().error(msg, ex);
        }
        return msg;
    }






    @PostMapping("/del")
    @ResponseBody
    public String del(Integer id){
        try{
            roleService.del(id);
            msg="角色删除成功！";
        }catch (RuntimeException ex){
            msg="角色删除失败！";
            Log.getLogger().error(msg,ex);
        }
        return msg;
    }

    @PostMapping("/batchDel")
    @ResponseBody()
    public String batchDel(Integer[] ids){
        try{
           roleService.bathDel(ids);
            msg="角色删除成功！";
        }catch (RuntimeException ex){
            msg="角色删除失败！";
            Log.getLogger().error(msg,ex);
        }
        return msg;
    }



}
